/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.listener;

import cn.hutool.core.collection.CollUtil;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.event.EsProductUpdateEvent;
import com.yami.shop.bean.event.PaySuccessOrderEvent;
import com.yami.shop.bean.event.PaySuccessScoreOrderEvent;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.order.PaySuccessOrderOrder;
import com.yami.shop.common.config.Constant;
import com.yami.shop.dao.ProdExtensionMapper;
import com.yami.shop.dao.ProductMapper;
import com.yami.shop.service.ShopWalletService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 支付成功回调
 *
 * @author LGH
 */
@Component("defaultPaySuccessListener")
@AllArgsConstructor
@Slf4j
public class PaySuccessOrderListener {

    private final ShopWalletService shopWalletService;
    private final ProdExtensionMapper prodExtensionMapper;
    private final ApplicationEventPublisher eventPublisher;

    @EventListener(PaySuccessOrderEvent.class)
    @Order(PaySuccessOrderOrder.SHOP_BILLING)
    public void shopPaySuccessListener(PaySuccessOrderEvent event) {
        List<com.yami.shop.bean.model.Order> orders = event.getOrders();
        // 如果是积分订单,直接退出
        if(Objects.equals(orders.get(0).getShopId(),Constant.PLATFORM_SHOP_ID)){
            return;
        }
        // 进行分账，添加一个分账记录表，因为每一个订单进行分完帐后要进行退款，那么退款的时候也应该按照下单的时候的分账比例进行原路返回
        shopWalletService.addAmountByOrder(orders);
        // 更新商品销量
        prodExtensionMapper.updateSoldNum(event.getAllOrderItems());
        List<Long> prodIds = new ArrayList<>();
        if (CollUtil.isNotEmpty(event.getAllOrderItems())) {
            prodIds = event.getAllOrderItems().stream().map(OrderItem::getProdId).collect(Collectors.toList());
        }
        // 更新es中的商品销量
        eventPublisher.publishEvent(new EsProductUpdateEvent(null, new ArrayList<>(prodIds), EsOperationType.UPDATE_BATCH));
    }

    @EventListener(PaySuccessScoreOrderEvent.class)
    @Order(PaySuccessOrderOrder.SHOP_BILLING)
    public void shopPaySuccessListener(PaySuccessScoreOrderEvent event) {
        com.yami.shop.bean.model.Order order = event.getOrder();
        // 进行平台分账，添加一个分账记录表
        shopWalletService.addAmountByScoreOrder(order);
    }
}
